/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package network.packets;

import datamodel.District;
import java.util.Vector;
import utils.StringUtils;
import utils.Utils;

/**
 *
 * @author Kvest
 */
public class DistrictsListResponce extends Packet
{
    private long listCreationTime;
    private Vector districts;
    
    public DistrictsListResponce(byte[] data)
    {
        super(DISTRICTS_LIST_RESPONCE, data);
    }
    
    protected void parse(byte[] data) 
    {
        int offset = 2;
        
        //время обновления списка районов в тиках
        byte[] tmp = new byte[8];
        System.arraycopy(data, offset, tmp, 0, tmp.length);
        offset += tmp.length;
        listCreationTime = Utils.byteToLong(tmp);
           
        //Размер массива районов
        tmp = new byte[4];
        System.arraycopy(data, offset, tmp, 0, tmp.length);
        offset += tmp.length;
        int size = Utils.byteToInt(tmp);
        
        //Районы
        districts = new Vector(size);
        int district_id;
        String name;
        for (int i = 0; i < size; ++i)
        {
            //id
            tmp = new byte[4];
            System.arraycopy(data, offset, tmp, 0, tmp.length);
            offset += tmp.length;
            district_id = Utils.byteToInt(tmp);
            
            //name
            System.arraycopy(data, offset, tmp, 0, tmp.length);
            offset += tmp.length;
            tmp = new byte[Utils.byteToInt(tmp)];
            System.arraycopy(data, offset, tmp, 0, tmp.length);
            offset += tmp.length;
            name = StringUtils.bytesToStr(tmp);
            
            //Добавляем район
            districts.addElement(new District(district_id, name));
        }
        
        System.gc();
    }
    
    public void print() 
    {
        String str = "DistrictsListResponce[listCreationTime=" + listCreationTime + "; {";
        District d;
        for (int i = 0; i < getDistrictsCount(); ++i)
        {
            d = getDistrict(i);
            str += d.getId() + "-" + d.getName() + ", ";
        }
        System.out.println(str + "}]");
    }
    
    public int getDistrictsCount()
    {
        return (districts != null ? districts.size() : 0);
    }
    
    public District getDistrict(int index)
    {
        return (District)districts.elementAt(index);
    }

    public long getListCreationTime() 
    {
        return listCreationTime;
    }
}
